const mongoose = require('mongoose');
const UserSchema = mongoose.model('UserSchema');
const Router = require('koa-router');
const UserRouter = new Router();
const request = require('request');

function getSensitive (api) {
  return new Promise((resolve, reject) => {
    request.get(api, (err, _, body) => {
      if (err) {
        reject(err);
      } else {
        resolve(body);
      }
    });
  })
}

UserRouter.get('/sensitiveData', async ctx => {
  try {
    const { code } =  ctx.request.query;
    //api接口,获取openid
    const appId = 'wx8858cdffdace248f', appSerect = '7a4cfd61c064556b3b19a04efb3330b4';
    const api = `https://api.weixin.qq.com/sns/jscode2session?appid=${appId}&secret=${appSerect}&js_code=${code}&grant_type=authorization_code`;
    const data = await getSensitive(api);
    ctx.body ={
      code: 200,
      data: JSON.parse(data),
    }
  } catch (error) {
    ctx.body = {
      code: 500,
      data: error,
    }
  }
})

UserRouter.post('/add', async ctx => {
  try {
    const { body } =  ctx.request;
    const listItem = await UserSchema.find({ openId: body.openId }).exec();
    if (listItem.length) {
      return ctx.body = {
        code: 500,
        data: '该用户已存在',
      }
    }
    await new UserSchema(body).save();
    ctx.body = {
      code: 200,
      data: '添加用户成功',
    }
  } catch (error) {
    ctx.body = {
      code: 500,
      data: error,
    }
  }
})

module.exports = UserRouter;